<?php



// 无限及分类菜单
function Navtree($list, $pid = 0, $level = 0, $html = '--')
{
    static $tree = array();
    foreach($list as $k=>$v){
        if($v['pid'] == $pid){
            $v['sort'] = $level;
            $v['html'] = str_repeat($html,$level);
            $tree[$k] = $v;
            Navtree($list,$v['id'],$level+1);
        }
    }
    return $tree;
}
//创建树形数组
function CreateTree($array,$pid=0){
    $result = array();
    foreach($array as $key => $val){
        if($val['pid'] == $pid) {
            $tmp = $array[$key];unset($array[$key]);
            count(createTree($array,$val['id'])) > 0 && $tmp['son'] = createTree($array,$val['id']);
            $result[$key] = $tmp;
        }
    }
    return $result;
}

/**
 * [p 打印输出函数]
 * @param  string $var [description]
 * @return [type]      [description]
 */
function p($var = "")
{
    if(is_bool($var)) {
        var_dump($var);
    } else if(is_null($var)) {
        var_dump(NULL);
    } else {
        echo "<pre style='position:relative;z-index:1000;padding:10px;border-radius:5px;background:#F5F5F5;border:1px solid #aaa;font-size:14px;line-height:18px;opacity:0.9;'>" . print_r($var, true) . "</pre>";
    }
}

/**
 * [LayerAlert 适用layer弹出框的提醒输出json]
 * @param [type] $b [提醒文字]
 * @param string $c [标题]
 * @param string $d [时间]
 */
function LayerAlert($b, $c = '提醒', $d = '2')
{
    return json_encode(array('content' => $b, 'title' => $c, 'time' => $d));
}

/**
 * [GetUrl 获取完整的url]
 */
function GetUrl()
{
    $pageURL = 'http';

    if($_SERVER["HTTPS"] == "on") {
        $pageURL .= "s";
    }
    $pageURL .= "://";

    if($_SERVER["SERVER_PORT"] != "80") {
        $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
    } else {
        $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
    }
    return $pageURL;
}

/**
 * [isNull 检测变量是否存在或者为空]
 * @param  [type]  $var     [传入的变量]
 * @param  string $default [传入的默认值]
 * @return boolean          [返回结果]
 */
function isNull($var, $default = '')
{
    if(isset($var)) {
        return !empty($var) ? $var : $default;
    }
}

/**
 * [jmc json_encode,message,code]
 * [jmc 返回指定格式的json字符串]
 * @param  [type] $m [消息]
 * @param  [type] $c [标识码]
 * @return [type]    [返回json]
 */
function json_mc($m, $c)
{
    $temp = json_encode(array('message' => $m, 'code' => $c));
    exit($temp);
}

/**
 * [ajaxReturn Ajax方式返回数据到客户端]
 * @param  [type]  $data        [传入的数据]
 * @param  string $type [类型]
 * @param  integer $json_option [description]
 * @return [type]               [description]
 */
function ajaxReturn($data, $type = '', $json_option = JSON_UNESCAPED_UNICODE)
{
    if(empty($type)) $type = 'JSON';
    switch (strtoupper($type)) {
        case 'JSON' :
            // 返回JSON数据格式到客户端 包含状态信息
            header('Content-Type:application/json; charset=utf-8');
            exit(json_encode($data, $json_option));
        case 'JSONP':
            // 返回JSON数据格式到客户端 包含状态信息
            header('Content-Type:application/json; charset=utf-8');
            $handler = isset($_GET['callback']) ? $_GET['callback'] : '';
            exit($handler . '(' . json_encode($data, $json_option) . ');');
        default     :
            print_r($data);
    }
}

/**
 * [https_request http模拟请求]
 * @param  [type] $url  [description]
 * @param  [type] $data [description]
 * @return [type]       [description]
 */
function https_request($url, $data = null)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    if(!empty($data)) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}

/**
 * [is_weixin 是否是微信浏览器]
 * @return boolean [description]
 */
function is_weixin()
{
    if(strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
        return true;
    }
    return false;
}

//设置session 过期时间
function start_session($expire = 0)
{
    if($expire == 0) {
        $expire = ini_get('session.gc_maxlifetime');
    } else {
        ini_set('session.gc_maxlifetime', $expire);
    }

    if(empty($_COOKIE['PHPSESSID'])) {
        session_set_cookie_params($expire);
        session_start();
    } else {
        session_start();
        setcookie('PHPSESSID', session_id(), time() + $expire);
    }
}

/*
*功能：php下载远程图片保存到本地
*参数：文件url,保存文件目录,保存文件名称，使用的下载方式
*当保存文件名称为空时则使用远程文件原来的名称
*/
function getImage($url, $save_dir = '', $filename = '', $type = 0)
{
    if(trim($url) == '') {
        return array('file_name' => '', 'save_path' => '', 'error' => 1);
    }
    if(trim($save_dir) == '') {
        $save_dir = './';
    }
    if(trim($filename) == '') {//保存文件名
        $ext = getImagesInfo($url);//获取图片后缀
        $filename = time() . '-' . uniqid() . $ext;
    }
    if(0 !== strrpos($save_dir, '/')) {
        $save_dir .= '/';
    }
    //创建保存目录
    if(!file_exists($save_dir) && !mkdir($save_dir, 0777, true)) {
        return array('file_name' => '', 'save_path' => '', 'error' => 5);
    }
    //获取远程文件所采用的方法
    if($type) {
        $ch = curl_init();
        $timeout = 5;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $img = curl_exec($ch);
        curl_close($ch);
    } else {
        ob_start();
        readfile($url);
        $img = ob_get_contents();
        ob_end_clean();
    }
    $size = strlen($img);
    //文件大小
    $fp2 = @fopen($save_dir . $filename, 'a');
    fwrite($fp2, $img);
    fclose($fp2);
    unset($img, $url);
    return array('file_name' => $filename, 'save_path' => $save_dir . $filename, 'time' => time(), 'size' => $size, 'error' => 0);
}


//获取图片的后缀
function getImagesInfo($img)
{
    $result = getimagesize($img);
    return '.' . substr($result['mime'], strpos($result['mime'], '/') + 1, 100);
}

/*中文不编码以及去掉/*/
function StrSpliData($arr)
{
    return stripslashes(json_encode($arr, JSON_UNESCAPED_UNICODE));
}

/*统一返回指定格式的歌曲信息*/
function ReturnMusicData($music, $title, $musicbg, $musicid, $musiclrc, $musicauth, $come, $len, $ext, $size)
{
    return array(
        'musicLink' => $music,//音乐链接
        'musicTitle' => $title,//歌曲名字
        'MusicBg' => $musicbg,//音乐背景图
        'MusicId' => $musicid,//音乐ID
        'MusicLrc' => $musiclrc,//歌词
        'MusicAuth' => $musicauth,//专辑
        'MusicCome' => $come,//歌曲来源
        'MusicLen' => $len,//歌曲长度
        'MusicExt' => $ext,//歌曲格式
        'MusicSize' => $size,//歌曲大小
    );
}

/*返回指定格式的歌曲列表*/
function ReturnMusicList($name, $auth, $id, $ext, $size, $come, $bz,$hd)
{
    return array(
        'MusicName' => $name,
        'MusicAuth' => $auth,
        'MusicId' => $id,
        'MusicSize' => $size,
        'MusicExt' => $ext,
        'MusicCome' => $come,
        'MusicBz' => $bz,
        'MusicHd' => $hd,
    );
}

/*返回当前网站根目录*/
function getPath(){
    return $_SERVER['DOCUMENT_ROOT'];
}
/*从Library目录引入指定的类*/
function RequireClass(){
    return 'App/Library/';
}
/*允许任何来源的post数据请求*/
function AllowCome(){
    Header("Access-Control-Allow-Origin:*");
    Header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
}
/*设置日志,传入日志名称*/
function Setlog($fileName,$data,$type='json'){
    if($type != 'json'){
        $data = json_encode($data,JSON_UNESCAPED_UNICODE);
    }
    return file_put_contents($_SERVER['DOCUMENT_ROOT'].'/Resources/log/'.$fileName,$data.PHP_EOL, FILE_APPEND);
}
/*获取日志,传入日志名称*/
function GetLog($fileName){
    return file_get_contents($_SERVER['DOCUMENT_ROOT'].'/Application/Runtime/Setlog/'.$fileName);
}
/*获取##中间的内容为标题,其他内容为内容*/
function GetTitleContent($str){
    $data = preg_match('/#([^#]+)#/', $str,$m);
    if (!empty($m)) {
        $content = str_replace($m[0], '', $str);
        $title = str_replace('#','',$m[0]);
        return [$title,$content];
    }else{
        return -1;
    }
}
function GetDbDet($keyword=''){
    include_once('Config/Dbfile/TextDbSend.php');
    foreach ($SendTempArr as $k => $v) {
        if ($v['keywords'] == $keyword) {
            $tempArr = $v;
            $tempArr['name'] = $k;
        }
    }
    return $tempArr;
}
/*xml转数组*/
function xmXmlToArrayl($xml)
{
    //将XML转为array
    $TempData = array();
    $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    foreach ($array_data as $k => $v)
    {
        $TempData[$k] = trim(str_replace(']]>','',str_replace('<![CDATA[','',$v)));
    }
    return $TempData;
}

/*生成guid*/
function guid($con='') {
    $charid = strtoupper(md5(uniqid(mt_rand(), true)));
    $hyphen = chr(45);// "-"
    $uuid = chr(123)// "{"
        .substr($charid, 0, 8).$hyphen
        .substr($charid, 8, 4).$hyphen
        .substr($charid,12, 4).$hyphen
        .substr($charid,16, 4).$hyphen
        .substr($charid,20,16)
        .chr(125);// "}"
    if (empty($con)) {
        $uuid = substr(str_replace('-','',$uuid),1,36);
    }else{
        $uuid = substr($uuid,1,36);
    }
    return $uuid;
}

/*载入指定的扩展文件*/
function Includes($name){
    require_once $_SERVER['DOCUMENT_ROOT'].'/App/Library/'.$name;
}
//删除空格
function trimall($str){
    $qian=array(" ","　","\t","\n","\r");
    $hou=array("","","","","");
    return str_replace($qian,$hou,$str);
}
/*引入composer主文件*/
function InclideVendor(){
    require $_SERVER['DOCUMENT_ROOT'].'/vendor/autoload.php';
}

/*ajax 快速返回数据*/
function ajaxReturnData($code,$mes,$data=''){
    ajaxReturn(array('code'=>$code,'mes'=>$mes,'data'=>$data));
}

/**
 * @param $keyword 关键词
 * @return bool 结果
 */
function _isYes($keyword){
    $data = ['是','恩','确','定','ok','好','就','这样','没','问','yes','成','同','意','en','o','当','然','必','须','开','哈','嗯'];
    return Trouble($data,$keyword);
}
function _isNo($keyword){
    $data = ['不','哦','no','不好','没','差','滚','非','拒'];
    return Trouble($data,$keyword);
}
/**
 * @param $data 结果集数组
 * @param $keyword 关键词
 * @return bool
 */
function Trouble($data,$keyword){
    $str = implode(',',$data);
    $tempKey = [];
    for ($i = 0; $i < mb_strlen($keyword); $i++) {
        $tempKey[] = mb_substr($keyword,$i,1);
    }
    for ($i = 0; $i < count($tempKey); $i++) {
        $find = mb_strpos($str,$tempKey[$i]);
        if(is_numeric($find)){
            return true;
        }
    }
    return false;
}
//快速获取post数据
function _post($data,$default=''){
    return I('post.'.$data,$default);
}
//快速获取get数据
function _get($data,$default=''){
    return I('get.'.$data,$default);
}
//是否是post提交
function _isPost(){
    return IS_POST;
}
//是否是ajax提交
function _isAjax(){
    return IS_AJAX;
}
function _Slog($info,$type='',$style='color:#009a61;font-size:14px;'){
    Includes('SocketLog/slog.function.php');
    slog(array( // /*参数配置*/
        'enable' => true,//是否打印日志的开关
        'host' => '114.113.152.151',//websocket服务器地址，默认localhost
        'optimize' => true,//是否显示利于优化的参数，如果运行时间，消耗内存等，默认为false
        'show_included_files' => false,//是否显示本次程序运行加载了哪些文件，默认为false
        'error_handler' => false,//是否接管程序错误，将程序错误显示在console中，默认为false
        'force_client_id' => 'zangxiangming',//日志强制记录到配置的client_id,默认为空
        'allow_client_ids' => array()////限制允许读取日志的client_id，默认为空,表示所有人都可以获得日志。
    ),'config');
    if($type){
        slog($info,$type,$style);
    }else{
        slog($info);
    }
}

/**判断某个值在不在当前数组中
 * @param $value 值
 * @param $array 数组
 * @return bool 返回结果
 */
function deep_in_array($value, $array) {
    foreach($array as $item) {
        if(!is_array($item)) {
            if ($item == $value) {
                return true;
            } else {
                continue;
            }
        }
        if(in_array($value, $item)) {
            return true;
        } else if(deep_in_array($value,$item)) {
            return true;
        }
    }
    return false;
}
/*数组转xml*/
function arrayToXml($arr, $dom = 0, $item = 0) {
    if (!$dom) {
        $dom = new DOMDocument("1.0");
    }
    if (!$item) {
        $item = $dom->createElement("root");
        $dom->appendChild($item);
    }
    foreach ($arr as $key => $val) {
        $itemx = $dom->createElement(is_string($key) ? $key : "item");
        $item->appendChild($itemx);
        if (!is_array($val)) {
            $text = $dom->createTextNode($val);
            $itemx->appendChild($text);
        } else {
            arrayToXml($val, $dom, $itemx);
        }
    }
    return $dom->saveXML();
}
/*数组转xml*/
function arrayToXml2($arr) {
    $xml = "<xml>";
    foreach ($arr as $key => $val) {
        if (is_array($val)) {
            $xml.="<" . $key . ">" . arrayToXml($val) . "</" . $key . ">";
        } else {
            $xml.="<" . $key . ">" . $val . "</" . $key . ">";
        }
    }
    $xml.="</xml>";
    return $xml;
}

//将XML转为array
function xmlToArray($xml) {
    //禁止引用外部xml实体
    libxml_disable_entity_loader(true);
    $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
    $val = json_decode(json_encode($xmlstring), true);
    return $val;
}

function Redis($key,$value,$exp=''){
    $redis = new Redis();
    if($key && $value){
        $redis->set($key,$value,$exp);
    }else{
        $redis->get($key);
    }
}
//获取时间字符串
function getStrtime($time=''){
    if(!$time) $time = time();
    return date('Y-m-d H:i:s',$time);
}

function console($str){
    $str = json_encode($str);
    echo "<script>console.log($str)</script>";
}
function isMobile2() {
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE'])){
        return true;
    }
    //如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset ($_SERVER['HTTP_VIA'])) {
        //找不到为flase,否则为true
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    }

    //判断手机发送的客户端标志,兼容性有待提高
    if (isset ($_SERVER['HTTP_USER_AGENT'])) {
        $clientkeywords = array (
            'nokia',
            'sony',
            'ericsson',
            'mot',
            'samsung',
            'htc',
            'sgh',
            'lg',
            'sharp',
            'sie-',
            'philips',
            'panasonic',
            'alcatel',
            'lenovo',
            'iphone',
            'ipod',
            'blackberry',
            'meizu',
            'android',
            'netfront',
            'symbian',
            'ucweb',
            'windowsce',
            'palm',
            'operamini',
            'operamobi',
            'openwave',
            'nexusone',
            'cldc',
            'midp',
            'wap',
            'mobile'
        );
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
            return true;
        }
    }
    //协议法，因为有可能不准确，放到最后判断
    if (isset ($_SERVER['HTTP_ACCEPT'])) {
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
            return true;
        }
    }
    return false;
}

/** 根据ip地址获取城市
 * @param $ip
 * @return mixed
 */
function ipGetCity($ip){
    $url = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=';
    $jsonStr = @file_get_contents($url.$ip);
    $json = substr(stristr($jsonStr,'{'),0,-1);
    return json_decode($json,true);
}
/** 友好的显示时间
 * @param $time
 * @return bool|string
 */
function formatTime($time){
    $now=time();
    $day=date('Y-m-d',$time);
    $today=date('Y-m-d');
    $dayArr=explode('-',$day);
    $todayArr=explode('-',$today);
    //距离的天数，这种方法超过30天则不一定准确，但是30天内是准确的，因为一个月可能是30天也可能是31天
    $days=($todayArr[0]-$dayArr[0])*365+(($todayArr[1]-$dayArr[1])*30)+($todayArr[2]-$dayArr[2]);
    //距离的秒数
    $secs=$now-$time;
    if($todayArr[0]-$dayArr[0]>0 && $days>3){//跨年且超过3天
        return date('Y-m-d',$time);
    }else{
        if($days<1){//今天
            if($secs<60){
                if($secs <0){
                    return '超时中';
                }else{
                    return '一分钟前';
                }
            }elseif($secs<3600){
                return floor($secs/60)."分钟前";
            }else{
                return floor($secs/3600)."小时前";
            }
        }else if($days<2){//昨天
            $hour=date('h',$time);
            return "昨天".$hour.'点';
        }elseif($days<3){//前天
            $hour=date('h',$time);
            return "前天".$hour.'点';
        }else{//三天前
            return date('m月d号',$time);
        }
    }
}
/**
 * [encrypt 数据加密]
 * @param  [type] $data [传入内容]
 * @param  [type] $key  [传入key]
 * @return [type]       [返回加密后的字符]
 */
function encrypt($data, $key='shala')
{
    $key	=	md5($key);
    $x		=	0;
    $len	=	strlen($data);
    $l		=	strlen($key);
    $char = '';
    for ($i = 0; $i < $len; $i++)
    {
        if ($x == $l)
        {
            $x = 0;
        }
        $char .= $key{$x};
        $x++;
    }
    $str = '';
    for ($i = 0; $i < $len; $i++)
    {
        $str .= chr(ord($data{$i}) + (ord($char{$i})) % 256);
    }
    return base64_encode($str);
}

/**
 * [decrypt 数据解密]
 * @param  [type] $data [传入加密数据]
 * @param  [type] $key  [传入key]
 * @return [type]       [返回解密结果]
 */
function decrypt($data, $key='shala')
{
    if(!$data) return false;
    $key = md5($key);
    $x = 0;
    $data = base64_decode($data);
    $len = strlen($data);
    $l = strlen($key);
    $char = '';
    for ($i = 0; $i < $len; $i++)
    {
        if ($x == $l)
        {
            $x = 0;
        }
        $char .= substr($key, $x, 1);
        $x++;
    }
    $str = '';
    for ($i = 0; $i < $len; $i++)
    {
        if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1)))
        {
            $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
        }
        else
        {
            $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
        }
    }
    return $str;
}
/*生成随机字符串*/
function UploadName($length = 32){
    $str = null;
    $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
    $max = strlen($strPol)-1;
    for($i=0;$i<$length;$i++){
        $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
    }
    return $str;
}

/** 获取图片大小及磁村
 * @param        $url
 * @param bool   $size
 * @param string $type
 * @param bool   $isGetFilesize
 * @return bool|string
 */
function getImgSize($url, $size=false, $type = 'curl', $isGetFilesize = true){
    // 若需要获取图片体积大小则默认使用 fread 方式
    // 或者使用 socket 二进制方式读取, 需要获取图片体积大小最好使用此方法
    $handle = fopen($url, 'rb');
    if (!$handle) return false;
    if($size){
        $type = $isGetFilesize ? 'fread' : $type;
        if ($type == 'fread') {
            // 只取头部固定长度168字节数据
            $dataBlock = fread($handle, 168);
        } else {
            // 据说 CURL 能缓存DNS 效率比 socket 高
            $ch = curl_init($url);
            // 超时设置
            curl_setopt($ch, CURLOPT_TIMEOUT, 5);
            // 取前面 168 个字符 通过四张测试图读取宽高结果都没有问题,若获取不到数据可适当加大数值
            curl_setopt($ch, CURLOPT_RANGE, '0-167');
            // 跟踪301跳转
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            // 返回结果
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $dataBlock = curl_exec($ch);
            curl_close($ch);
            if (!$dataBlock) return false;
        }
        // 将读取的图片信息转化为图片路径并获取图片信息,经测试,这里的转化设置 jpeg 对获取png,gif的信息没有影响,无须分别设置
        // 有些图片虽然可以在浏览器查看但实际已被损坏可能无法解析信息
        $size = getimagesize('data://image/jpeg;base64,' . base64_encode($dataBlock));
        if (empty($size)) {
            return false;
        }
        $result['width'] = $size[0];
        $result['height'] = $size[1];
    }
    // 是否获取图片体积大小
    if ($isGetFilesize) {
        // 获取文件数据流信息
        $meta = stream_get_meta_data($handle);
        // nginx 的信息保存在 headers 里，apache 则直接在 wrapper_data
        $dataInfo = isset($meta['wrapper_data']['headers']) ? $meta['wrapper_data']['headers'] : $meta['wrapper_data'];
        foreach ($dataInfo as $va) {
            if (preg_match('/length/iU', $va)) {
                $ts = explode(':', $va);
                $result['size'] = trim(array_pop($ts));
                break;
            }
        }
    }
    if ($type == 'fread') fclose($handle);
    return $result['size'];
}

function getCache($key){
    $path = $_SERVER['DOCUMENT_ROOT'].'/Resources/fileDB/cache/'.md5($key).'.cache';
    $data = file_get_contents($path);
    return unserialize($data);
}
function setCache($key,$value){
    $path = $_SERVER['DOCUMENT_ROOT'].'/Resources/fileDB/cache/'.md5($key).'.cache';
    return file_put_contents($path,serialize($value));
}
function delCache($key){
    $path = $_SERVER['DOCUMENT_ROOT'].'/Resources/fileDB/cache/'.md5($key).'.cache';
    return rmdir($path);
}

//删除目录及下面所有文件
function delAlldir($dir) {
    $dh = opendir($dir);
    while ($file = readdir($dh)) {
        if($file!="." && $file!="..") {
            $fullpath=$dir."/".$file;
            if(!is_dir($fullpath)) {
                unlink($fullpath);
            } else {
                delAlldir($fullpath);
            }
        }
    }
    closedir($dh);
    if(rmdir($dir)) {
        return true;
    } else {
        return false;
    }
}

function getHost($host){
    if($host == 1){
        return 'http://img.he29.com/';
    }else{
        return 'http://file.he29.com';
    }
}

//无限极分类
function generateTree($items,$pid = 'father',$son='children'){
    $tree = array();
    foreach($items as $item){
        if(isset($items[$item['father']])){
            if(!empty($items[$item['id']])){
                $items[$item[$pid]][$son][] = &$items[$item['id']];
            }
        }else{
            $tree[] = &$items[$item['id']];
        }
    }
    return $tree;
}

function getFind($id='id'){
    $preg = '/[\W\w][?|&]'.$id.'=\d+/';
    preg_match_all($preg,$_SERVER['REQUEST_URI'],$all);
    return explode('=',current($all)[0])[1];
}

function get_url($host = true) {
    $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
    $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
    $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
    $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.$_SERVER['QUERY_STRING'] : $path_info);
    if($host){
        return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
    }else{
        return (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
    }
}

function setCook($key,$name){
    setcookie($key,$name,time()+3600*24*7,'/','.he29.com');
}

function https_curl($url, $data = null,$config=[]){

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($curl, CURLOPT_REFERER, isset($config['come'])?$config['come']:'');   //构造来路
    curl_setopt($curl, CURLOPT_USERAGENT, isset($config['ua'])?$config['ua']:'');   //构造来路
    if(!empty($data)) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl,CURLOPT_COOKIE,isset($config['cookie'])?$config['cookie']:'');
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}
function mkdirs($dir, $mode = 0777)
{
    if (is_dir($dir) || @mkdir($dir, $mode)) return true;
    if (!mkdirs(dirname($dir), $mode)) return false;
    return @mkdir($dir, $mode);
}

/** 在数组里随机取
 * @param     $arr
 * @param int $num
 */
function arrLimit($arr,$num=2){
    $temp=array_rand($arr,$num);
    $data_last = [];
    foreach($temp as $val){
        $data_last[] = $arr[$val];
    }
    return $data_last;
}
function rsyncd($url,$data=[],$time=60){
    $curl = curl_init();
    set_time_limit(0);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    if(!empty($data)) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl,CURLOPT_TIMEOUT,$time);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}

function required($name='vendor'){
    require_once $_SERVER['DOCUMENT_ROOT'].'/'.$name.'/autoload.php';
}

function resyncTest($url){
    $ch = curl_init();
    $curl_opt = array(CURLOPT_URL,$url,
        CURLOPT_RETURNTRANSFER, 1,
        CURLOPT_TIMEOUT, 10,);
    curl_setopt_array($ch,$curl_opt);
    curl_exec($ch);
    curl_close($ch);
}
function logger($name,$re){
    $path = $_SERVER['DOCUMENT_ROOT'].'/log/send/'.$name.'.log';
    file_put_contents($path,json_encode($re).PHP_EOL,FILE_APPEND);
}
function sysGET($name){
    return $_REQUEST[$name];
}

/**是否存在
 * @return bool
 */
function isNav($name='iframe'){
    if($_REQUEST[$name]){
        return true;
    }else{
        return false;
    }
}

/** 几天前
 * @param $the_time
 * @return string
 */
function time_tran($the_time) {
    $now_time = date("Y-m-d H:i:s", time());
    $now_time = strtotime($now_time);
    $show_time = strtotime($the_time);
    $dur = $now_time - $show_time;
    if ($dur < 0) {
        return $the_time;
    } else {
        if ($dur < 60) {
            return $dur . '秒前';
        } else {
            if ($dur < 3600) {
                return floor($dur / 60) . '分钟前';
            } else {
                if ($dur < 86400) {
                    return floor($dur / 3600) . '小时前';
                } else {
                    if ($dur < 259200) {//3天内
                        return floor($dur / 86400) . '天前';
                    } else {
                        return date('Y-m-d',strtotime($the_time));
                    }
                }
            }
        }
    }
}
define('PI',3.1415926535898);
define('EARTH_RADIUS',6378.137);

//计算范围，可以做搜索用户
function GetRange($lat,$lon,$raidus){
    //计算纬度
    $degree = (24901 * 1609) / 360.0;
    $dpmLat = 1 / $degree;
    $radiusLat = $dpmLat * $raidus;
    $minLat = $lat - $radiusLat; //得到最小纬度
    $maxLat = $lat + $radiusLat; //得到最大纬度
    //计算经度
    $mpdLng = $degree * cos($lat * (PI / 180));
    $dpmLng = 1 / $mpdLng;
    $radiusLng = $dpmLng * $raidus;
    $minLng = $lon - $radiusLng; //得到最小经度
    $maxLng = $lon + $radiusLng; //得到最大经度
    //范围
    $range = array(
        'minLat' => $minLat,
        'maxLat' => $maxLat,
        'minLon' => $minLng,
        'maxLon' => $maxLng
    );
    return $range;
}
//获取2点之间的距离
function GetDistance($lat1, $lng1, $lat2, $lng2, $len_type = 1, $decimal = 2){
    $radLat1 = $lat1 * PI / 180.0;
    $radLat2 = $lat2 * PI / 180.0;
    $a = $radLat1 - $radLat2;
    $b = ($lng1 * PI / 180.0) - ($lng2 * PI / 180.0);
    $s = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
    $s = $s * EARTH_RADIUS;
    $s = round($s * 1000);
    if ($len_type > 1)
    {
        $s /= 1000;
    }
    return round($s, $decimal);
}

function enhex($str,$key='123') {
    /* 开启加密算法/ */
    $td = mcrypt_module_open('twofish', '', 'ecb', '');
    /* 建立 IV，并检测 key 的长度 */
    $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
    $ks = mcrypt_enc_get_key_size($td);
    /* 生成 key */
    $keystr = substr(md5($key), 0, $ks);
    /* 初始化加密程序 */
    mcrypt_generic_init($td, $keystr, $iv);
    /* 加密, $encrypted 保存的是已经加密后的数据 */
    $encrypted = mcrypt_generic($td, $str);
    /* 检测解密句柄，并关闭模块 */
    mcrypt_module_close($td);
    /* 转化为16进制 */
    $hexdata = bin2hex($encrypted);
    //返回
    return $hexdata;
}

function dehex($str,$key='123') {
    /* 开启加密算法/ */
    $td = mcrypt_module_open('twofish', '', 'ecb', '');
    /* 建立 IV，并检测 key 的长度 */
    $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
    $ks = mcrypt_enc_get_key_size($td);
    /* 生成 key */
    $keystr = substr(md5($key), 0, $ks);
    /* 初始化加密模块，用以解密 */
    mcrypt_generic_init($td, $keystr, $iv);
    /* 解密 */
    $encrypted = pack("H*", $str);
    $decrypted = mdecrypt_generic($td, $encrypted);
    /* 检测解密句柄，并关闭模块 */
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
    /* 返回原始字符串 */
    return $decrypted;
}

function getguid($length = 32){
    $charid = strtolower(md5(uniqid(rand(), true)));
    if($length == 16)
        $charid = substr($charid,8,16);
    return $charid;
}
//获取图片的RGB信息,如果RGB中 128,128,128 出现次数大于1024个像素点,则此图可能切图失败
function imgColor($path){
    $i=imagecreatefromjpeg($path);//图片路径
    $num = 1;
    for ($x=0;$x<imagesx($i);$x++) {
        $num++;
        for ($y=0;$y<imagesy($i);$y++) {
            $rgb = imagecolorat($i,$x,$y);
            $r = ($rgb>>16) & 0xFF;
            $g = ($rgb>>8) & 0xFF;
            $b = $rgb & 0xFF;
            print_r("($r,$g,$b)");
            if($num == 1000){
                break;
            }
        }
    }
}

function getHello(){
    $hour =date('H',time());
    if($hour < 6){
        return "又是一个不眠夜";
    }else if ($hour < 9){
        return "新的一天开始啦";
    }else if ($hour < 12){
        return "上午工作顺利吗";
    }else if ($hour < 14){
        return "中午好！吃了吗";
    }else if ($hour < 17){
        return "下午好!别打盹哦";
    }else if ($hour < 19){
        return "傍晚好!下班了";
    }else if ($hour < 22){
        return "晚上好!夜色多美啊";
    }else {
        return "夜深了,早点睡哦";
    }
}

function isMobile()
{
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
    {
        return true;
    }
    // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset ($_SERVER['HTTP_VIA']))
    {
        // 找不到为flase,否则为true
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    }
    // 脑残法，判断手机发送的客户端标志,兼容性有待提高
    if (isset ($_SERVER['HTTP_USER_AGENT']))
    {
        $clientkeywords = array ('nokia',
            'sony',
            'ericsson',
            'mot',
            'samsung',
            'htc',
            'sgh',
            'lg',
            'sharp',
            'sie-',
            'philips',
            'panasonic',
            'alcatel',
            'lenovo',
            'iphone',
            'ipod',
            'blackberry',
            'meizu',
            'android',
            'netfront',
            'symbian',
            'ucweb',
            'windowsce',
            'palm',
            'operamini',
            'operamobi',
            'openwave',
            'nexusone',
            'cldc',
            'midp',
            'wap',
            'mobile'
        );
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
        {
            return true;
        }
    }
    // 协议法，因为有可能不准确，放到最后判断
    if (isset ($_SERVER['HTTP_ACCEPT']))
    {
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html'))))
        {
            return true;
        }
    }
    return false;
}
function getExtension($file)
{
    return '.'.substr(strrchr($file, '.'), 1);
}
function setlogs($str,$name='',$lev=3,$nameType='info'){
    $type = 'text';
    if(!is_array($str)){
        $inputData = $str;
    }else{
        $inputData = json_encode($str,JSON_UNESCAPED_UNICODE);
        $type = 'array';
    }
    $insert = '['.$name.'('.$type.')]['.date('Y-m-d H:i:s',time()).']'.PHP_EOL.'-------------------------------------'.PHP_EOL.$inputData.PHP_EOL.'-------------------------------------'.PHP_EOL;
    file_put_contents($_SERVER['DOCUMENT_ROOT'].'/public/log/info.log',$insert,FILE_APPEND);
}
//$array 要排序的数组
//$row  排序依据列
//$type 排序类型[asc or desc]
//return 排好序的数组
function array_sort($array,$row,$type){
    $array_temp = array();
    foreach($array as $v){
        $array_temp[$v[$row]] = $v;
    }
    if($type == 'asc'){
        ksort($array_temp);
    }elseif($type='desc'){
        krsort($array_temp);
    }else{
    }
    return $array_temp;
}